<?php
class Core_Group implements Iterator, Countable {
	protected $_key;
	protected $_conteiner;
	protected $_map;
	protected $_key_save;
	
	public function __construct(array $data, $key, $key_save = true) {
		if (sizeof ( $data ) <= 1)
			return $data;
		$this->_key_save = $key_save;
		if (! is_array ( $data [0] ) || ! array_key_exists ( $key, $data [0] ))
			return null;
		
		$this->_key = $key;
		$this->_map = array ();
		$this->_conteiner = $data;
		
		foreach ( $this->_conteiner as $key => $value ) {
			if (! array_key_exists ( $key_val = $value [$this->_key], $this->_map ))
				$this->_map [$key_val] = array ();
			
			array_push ( $this->_map [$key_val], $key );
		}
	}
	
	public function count() {
		return sizeOf ( $this->_map );
	}
	
	public function current() {
		$result = array ();
		$c = 0;
		foreach ( current ( $this->_map ) as $value )
			$result [$this->_key_save ? $value : $c ++] = $this->_conteiner [$value];
		return $result;
	}
	
	public function next() {
		next ( $this->_map );
	}
	
	public function key() {
		key ( $this->_map );
	}
	
	public function valid() {
		return is_array ( current ( $this->_map ) );
	}
	
	public function rewind() {
		reset ( $this->_map );
	}
}